package basics.files;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

public class ReadWriteToFile {

    public static void main(String[] args) {

        String contents=read("/Users/ken/dummy.txt");
        write("/Users/ken/dummy.txt","Good day!");
        System.out.println(contents);
    }

    /**
     * Reading from a file
     * @param filepath, the absolute file path
     * @return the content as a string
     */
    public static String read(String filepath)
    {   
        File theFile = new File(filepath);
        byte[] bytes = new byte[(int) theFile.length()];
        InputStream in;
        try {

            in = new FileInputStream(theFile);
            in.read(bytes);
            in.close();   

        } catch (Exception e) {
            e.printStackTrace();
        }

        return new String(bytes); 
    }

    /**
     * Writes something to a file, overwrites the old content
     * if the file doesn't exist, it will create a new file
     * @param filepath, the absolute file path
     * @param content, the content to write to the file
     */
    public static void write(String filepath, String content)
    {

        try {

            File file = new File(filepath);

            // if file doesnt exists, then create it
            if (!file.exists()) {    
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();

            System.out.println("Done");

        } catch (IOException e) {
                e.printStackTrace();
        }
    }

}
